import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Layout, Menu, Icon } from 'antd';
import {connect} from 'react-redux'
import menuList from '../../config/menuConfig'
import './index.less';
import logo from '../../assets/images/logo.svg'
const { Sider } = Layout;
const { SubMenu } = Menu;

function LogoTitle(props) {
  return (
    <h1>商城管理后台</h1>
  );
}
class MySider extends Component{
  state={
    path: '', // 当前路由，高亮
    openKey: '' // 需要打开的路由
  }
  UNSAFE_componentWillMount(){
    const pathname = this.props.location.pathname
    let strLength = pathname.split('/')
    if(strLength.length > 1){
      this.setState({
        openKey: '/' + strLength[1]
      })
    }
    this.getMenuNodes_map();
    this.setState({
      path: pathname
    })
  }
  // 只展开当前菜单项
  onOpenChange = openKeys => {
    const latestOpenKey = openKeys.find(key => this.state.openKey.indexOf(key) === -1)
    this.setState({
      openKey: latestOpenKey ? latestOpenKey : ''
    })
  }
  /**
   * 用返回的菜单数据与本地做对比，生成当前用户的侧边栏
   */
  getMenuNodes_map = () => {
    let pre = []
    menuList.map(item => {
      // 动态获取左侧列表，第一版不用
      // if(this.props.user.loginName==='admin'){
      if(this.props.user.role.menus.length===0){
        pre = menuList
      } else {
        this.props.user.role.menus.forEach(val => {
          if(item.children){
            item.children.map(value => {
              if(value.key === val){
                item.children = []
                item.children.push(value)
                pre.push(item)
              }
            })
          } else {
            if(item.key === val){
              pre.push(item)
            }
          }
        })
      }
    })
    this.setState({
      pre:this.renderMenu(pre)
    })
  }
  // 菜单渲染
  renderMenu = (data) => {
    return data.map((item) => {
      if(item.children && item.children.length > 0) {
        return <SubMenu key={item.key} title={<span><Icon type={item.icon} /><span>{item.title}</span></span>}>
          {
            item.children.map(val => {
              return <Menu.Item key={val.key} title={val.title}><Link to={val.key}><span>{val.title}</span></Link></Menu.Item>
            })
          }
        </SubMenu>
      } else {
        return <Menu.Item key={item.key} title={item.title}><Link to={item.key}><Icon type={item.icon} /><span>{item.title}</span></Link></Menu.Item>
      }
    })
  }
  render() {
    return (
      <Sider className="nav" style={{overflow: 'auto',height: '100vh',position: 'fixed',left: 0,}}>
        <div className="logo">
          <img src={logo} alt="logo" />
          <LogoTitle>商城管理后台</LogoTitle>
        </div>
        <Menu mode="inline" theme="dark" defaultSelectedKeys={[this.state.path]} openKeys={[this.state.openKey]} onOpenChange={this.onOpenChange}>
          {this.state.pre}
        </Menu>
      </Sider>
    )
  }
}
export default connect(
  state => ({user: state.user})
)(withRouter(MySider))